#!/bin/sh

EEPROM_LOCATION="/sys/bus/i2c/drivers/at24/2-0050/eeprom"
OFFSET=0
DATA_LENGTH=8
DUMP_FORMAT="$DATA_LENGTH/1 \"%c\""
WRITE_DATA="01234567"
ORIGIN_DATA=""

show_help()
{                                                  
    echo -e "Usage:\n $0 [options]\n\n\ EEPROM write and read back test\n\n\
Options:\n\
 -i <write data>    data written to the eeprom\n\
 -o <file path>     file path to the eeprom\n\
                    (default:$EEPROM_LOCATION)\n"
} 


my_test()
{
	# PATH
	echo -e "EEPROM_LOCATION: $EEPROM_LOCATION"
	
	cp $EEPROM_LOCATION /tmp/originalEepromData

	ORIGIN_DATA=$(hexdump -s $OFFSET -n $DATA_LENGTH \
                -e "$DUMP_FORMAT" $EEPROM_LOCATION)
	echo -e "ORIGIN_DATA: $ORIGIN_DATA"
 
	# Write data to EEPROM
	echo -e "WRITE_DATA: $WRITE_DATA"
	echo -n -e "$WRITE_DATA" > $EEPROM_LOCATION

	# Read data from EEPROM
	READ_DATA=$(hexdump -n $DATA_LENGTH \
		-e "$DUMP_FORMAT" $EEPROM_LOCATION)
	echo -e "READ_DATA:  $READ_DATA"

	if [[ "$READ_DATA" = "$WRITE_DATA" ]]; then
		echo PASS
	else
		echo FAIL
	fi
	
	# Write original data back
	#echo -n -e "$ORIGIN_DATA" > $EEPROM_LOCATION
	cat /tmp/originalEepromData > $EEPROM_LOCATION
	rm /tmp/originalEepromData

        # Make sure the original data is recovery
        READ_DATA=$(hexdump -n $DATA_LENGTH \
                -e "$DUMP_FORMAT" $EEPROM_LOCATION)
	
	if [[ ! "$READ_DATA" = "$ORIGIN_DATA" ]]; then
                echo "Error: Write original data back FAIL"
		echo "FAIL"
        fi	
}


# A POSIX variable
OPTIND=1         # Reset in case getopts has been used previously in the shell.

while getopts "i:o:h?" opt; do
	case "$opt" in
	i)
		WRITE_DATA=$OPTARG
		DATA_LENGTH=${#WRITE_DATA}
		DUMP_FORMAT="$DATA_LENGTH/1 \"%c\""
		;;
	o)
		EEPROM_LOCATION=$OPTARG
		;;
	h|\?)
		show_help
		exit 0
		;;
	esac
done

shift $((OPTIND-1))

my_test
